package com.shycloud.mido.music.service.impl;

import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.huaban.analysis.jieba.JiebaSegmenter;
import com.huaban.analysis.jieba.SegToken;
import com.huaban.analysis.jieba.WordDictionary;
import com.shycloud.mido.common.security.util.SecurityUtils;
import com.shycloud.mido.music.dto.MisMusicCollectionDTO;
import com.shycloud.mido.music.vo.MisMusicVO;
import lombok.AllArgsConstructor;
import org.springframework.stereotype.Service;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.shycloud.mido.music.mapper.MisHotHistoryMapper;
import com.shycloud.mido.music.domain.MisHotHistory;
import com.shycloud.mido.music.service.MisHotHistoryService;

import java.io.File;
import java.math.BigDecimal;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.util.*;
import java.util.stream.Collectors;

@Service
@AllArgsConstructor
public class MisHotHistoryServiceImpl extends ServiceImpl<MisHotHistoryMapper, MisHotHistory> implements MisHotHistoryService {

	/**
	 * 检索模块 mapper
	 */
	private MisHotHistoryMapper misHotHistoryMapper;

	/**
	 * 检索曲集
	 *
	 * @param page
	 * @param keyword
	 * @return com.baomidou.mybatisplus.core.metadata.IPage<com.shycloud.mido.music.vo.MyCollectionVO>
	 * @author nianhua.jiang
	 * @date 2020/7/1 18:56
	 */
	@Override
	public IPage<MisMusicCollectionDTO> searchCollection(Page page, String keyword, String flg) {

		// 词典路径为 resource/dicts/fenci.dict
		Path path = Paths.get(new File(getClass().getClassLoader().getResource("dicts/fenci.dict").getPath()).getAbsolutePath());
		//加载自定义的词典进词库
		WordDictionary.getInstance().loadUserDict(path);
		//重新分词
		JiebaSegmenter segmenter = new JiebaSegmenter();

		List<SegToken> process = segmenter.process(keyword, JiebaSegmenter.SegMode.SEARCH);

		Iterator<SegToken> iterator = process.iterator();

		while (iterator.hasNext()) {
			if ("的".equals(iterator.next().word)) {
				iterator.remove();
			}
		}

		IPage<MisMusicCollectionDTO> result = null;
		if (SecurityUtils.getMember() != null) {
			result = misHotHistoryMapper.searchCollection(page, process, SecurityUtils.getMember().getId(), flg);
		} else {
			result = misHotHistoryMapper.searchCollection(page, process, "没有", flg);
		}

		if (result.getRecords() == null || result.getRecords().size() == 0) {
			List<SegToken> processIfNull = new ArrayList<>();
			keyword = keyword.substring(0, 1);
			processIfNull.add(new SegToken(keyword, 0, 1));
			result = misHotHistoryMapper.searchCollection(page, processIfNull, SecurityUtils.getMember() == null ? "没有" : SecurityUtils.getMember().getId(), flg);
		}

		Set<String> keywordList = Arrays.asList(keyword.split("")).stream().collect(Collectors.toSet());
		List<MisMusicCollectionDTO> collectionResult = result.getRecords();

		for (MisMusicCollectionDTO coll : collectionResult) {
			String[] split = coll.getName().split("");

			BigDecimal keywordLength = new BigDecimal(coll.getName().length());

			for (String s : split) {
				if (keywordList.contains(s)) {
					BigDecimal i = coll.getFrequency();

					BigDecimal temp = new BigDecimal(1);

					BigDecimal target = temp.divide(keywordLength, 2, BigDecimal.ROUND_HALF_UP);

					if (i == null) {
						coll.setFrequency(target);
					} else {
						coll.setFrequency(i.add(target));
					}
				}
			}
		}

		List<MisMusicCollectionDTO> collect = collectionResult.stream().sorted().collect(Collectors.toList());
		result.setRecords(collect);
		return result;
	}

	/**
	 * 搜索曲目
	 *
	 * @param page
	 * @param keyword
	 * @return com.baomidou.mybatisplus.core.metadata.IPage<com.shycloud.mido.music.vo.MisMusicVO>
	 * @author nianhua.jiang
	 * @date 2020/7/2 9:40
	 */
	@Override
	public IPage<MisMusicVO> searchMusic(Page page, String keyword, String isCustom) {

		IPage<MisMusicVO> result = null;

		if (keyword.length() <= 2) {
			SegToken segToken = new SegToken(keyword, 0, 0);
			List<SegToken> process = new ArrayList<>();
			process.add(segToken);
			if (SecurityUtils.getMember() != null) {
				result = misHotHistoryMapper.searchMusic(page, keyword, process, SecurityUtils.getMember().getId(), isCustom);
			} else {
				result = misHotHistoryMapper.searchMusic(page, keyword, process, "无token情况", isCustom);
			}
		} else {

			// 词典路径为 resource/dicts/fenci.dict
			Path path = Paths.get(new File(getClass().getClassLoader().getResource("dicts/fenci.dict").getPath()).getAbsolutePath());
			//加载自定义的词典进词库
			WordDictionary.getInstance().loadUserDict(path);
			//重新分词
			JiebaSegmenter segmenter = new JiebaSegmenter();

			List<SegToken> process = segmenter.process(keyword, JiebaSegmenter.SegMode.SEARCH);

			Iterator<SegToken> iterator = process.iterator();

			while (iterator.hasNext()) {
				if (iterator.next().word.length() == 1) {
					iterator.remove();
				}
			}

			if (SecurityUtils.getMember() != null) {
				result = misHotHistoryMapper.searchMusic(page, keyword, process, SecurityUtils.getMember().getId(), isCustom);
			} else {
				result = misHotHistoryMapper.searchMusic(page, keyword, process, "无token情况", isCustom);
			}
		}

		if (result.getRecords() == null || result.getRecords().size() == 0) {
			List<SegToken> processIfNull = new ArrayList<>();
			keyword = keyword.substring(0, 1);
			processIfNull.add(new SegToken(keyword, 0, 1));
			result = misHotHistoryMapper.searchMusic(page, keyword, processIfNull, SecurityUtils.getMember() == null ? "没有" : SecurityUtils.getMember().getId(), isCustom);
		}

		Set<String> keywordList = Arrays.asList(keyword.split("")).stream().collect(Collectors.toSet());

		List<MisMusicVO> musicResult = result.getRecords();

		for (MisMusicVO misMusicVO : musicResult) {

			String[] split = misMusicVO.getName().split("");

			BigDecimal keywordLength = new BigDecimal(misMusicVO.getName().length());

			for (String s : split) {
				if (keywordList.contains(s)) {

					BigDecimal i = misMusicVO.getFrequency();

					BigDecimal temp = new BigDecimal(1);

					BigDecimal target = temp.divide(keywordLength, 2, BigDecimal.ROUND_HALF_UP);

					if (i == null) {
						misMusicVO.setFrequency(target);
					} else {
						misMusicVO.setFrequency(i.add(target));
					}
				}
			}

			if (keyword.equals(misMusicVO.getName())) {
				misMusicVO.setFrequency(new BigDecimal("2.00"));
			}

		}
		List<MisMusicVO> collect = musicResult.stream().sorted().collect(Collectors.toList());
		result.setRecords(collect);
		return result;
	}

}

